<template>
  <div class="content">
    <div class="top_bg"></div>

    <h3 class="report_title" style="">
      <el-popover placement="bottom" width="200" trigger="hover">
        <span slot="reference">{{ title }}</span>
        <p
          style="cursor: pointer"
          v-for="id in dataInfo.children"
          :key="id"
          @click="selectPharse(listsById[id])"
        >
          {{ listsById[id].name }}
        </p>
      </el-popover>
      <span class="right">
        <el-popover placement="bottom" title="提示" width="200" trigger="click">
          <p>未开始：该项处于创建状态；</p>
          <p>进行中：该项非创建和完成状态，且当前日期小于等于计划完成日期；</p>
          <p>完成：该项处于完成状态，且实际完成日期小于等于计划完成日期；</p>
          <p>延期完成：该项处于完成状态，且实际完成日期大于计划完成日期；</p>
          <p>
            延期未完成：该项非创建和完成状态，且实际完成日期大于计划完成日期。
          </p>
          <i class="el-icon-info" slot="reference"></i>
        </el-popover>
      </span>
    </h3>

    <div class="report_all">
      <el-card class="box-card" v-scrollbar>
        <div slot="header" class="clearfix">
          <span>所有任务</span>
        </div>
        <polar-bar
          :title="''"
          :name="'allTasks'"
          :dataList="allTasks"
          :rend="rend"
          @handleClick="handleClick"
        ></polar-bar>
        <div class="listItem">
          <img src="@/assets/image/ico_percent.png" alt="" />
          <span>进度</span>
          <span class="right">
            <count-to
              :start-val="0"
              :end-val="panels.delayDays < 0 ? 0 : panels.percent"
              :duration="3000"
            ></count-to
            >%
          </span>
        </div>
        <div class="listItem">
          <img src="@/assets/image/ico_delayday.png" alt="" />
          <span>延迟天数</span>
          <span class="right">
            <count-to
              :start-val="0"
              :end-val="panels.delayDays < 0 ? 0 : panels.delayDays"
              :duration="3000"
            ></count-to
            >天
          </span>
        </div>
        <div class="listItem">
          <img src="@/assets/image/ico_delaytask.png" alt="" />
          <span>延迟任务</span>
          <span class="right">
            <count-to
              :start-val="0"
              :end-val="panels.delayDays < 0 ? 0 : panels.delayDays"
              :duration="3000"
            ></count-to
            >%
            <span style="display:inline-block;width:75px;font-size: 12px; color: #f56c6c;position:absolute;right:-30px;bottom:-16px;"
              >{{
                panels.delayTasks
                  ? panels.delayTasks.filter((item) => item.iskeytask).length
                  : 0
              }}个关键</span
            >
          </span>
        </div>
        <div class="listItem" v-for="item in rateofachieve" :key="item.name">
          <img src="@/assets/image/ico_keytask.png" alt="" />
          <span>{{ item.name }}</span>
          <span class="right">
            <count-to
              :start-val="0"
              :end-val="item.rate"
              :duration="3000"
            ></count-to
            >%
            <span style="display:inline-block;width:75px;font-size:12px;color:#999;position:absolute;right:-20px;bottom:-16px;">节点达成率</span>
          </span>
        </div>
      </el-card>
    </div>
    <div class="report_stage">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>顶层任务</span>
        </div>
        <div class="stageTasks" ref="stageTasks"></div>
      </el-card>
    </div>
    <div class="report_tasks">
      <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>交付内容</span>
  </div>
 
      <pie-access
        :title="'交付内容'"
        :name="'delivers'"
        :dataList="delivers"
        :rend="rend"
        @handleClick="handleClick"
      ></pie-access>
</el-card>
<el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>关键任务</span>
  </div>
      <pie-bar
        :title="'关键任务'"
        :name="'keyTasks'"
        :dataList="keyTasks"
        :rend="rend"
        @handleClick="handleClick"
      ></pie-bar>
</el-card>
    </div>
  </div>
</template>

<script>
import CountTo from "vue-count-to";
import pieBar from "./pieBar.vue";
import polarBar from "./polarBar.vue";
import pieAccess from "./pieAccess.vue";
import * as echarts from "echarts";
import resize from "./mixins/resize";
import dynamicTable from "@/views/components/dynamicTable";
import { getDataList, getData, getTableCol } from "@/api/dynamic/dynamic";
var that;
export default {
  inject: ["app"],
  name: "report",
  mixins: [resize],
  components: {
    dynamicTable,
    CountTo,
    pieBar,
    pieAccess,
    polarBar
  },
  data() {
    return {
      chart: null,
      title: "",
      dataInfo: {},
      allData: [],
      listsById: null,
      listTree: null,
      newList: [],
      currentStage: null,
      rend: false,
      topen: false,
      panels: {
        percent: 90,
        delayDays: 0,
        delayTasks: [],
        members: [],
      },
      rateofachieve: [],
      stageTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      allTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      delivers: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      keyTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: false, // 是否支持列表项选中功能
      },
      operates: {
        // 列操作按钮
        width: 150,
        list: [],
      },
      tableData: [],
      tableColumns: [
        {
          name: "名称",
          prop: "name",
        },
        {
          name: "类型",
          prop: "typeid",
        },
        {
          name: "策略",
          prop: "policyid",
        },
        {
          name: "状态",
          prop: "stateid",
        },
        {
          name: "描述",
          prop: "description",
        },
        {
          name: "创建时间",
          prop: "createTime",
        },
        {
          name: "修改时间",
          prop: "modifyTime",
        },
      ],
    };
  },
  created() {
    // this.getTableColumns();
    this.getDataInfo();
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
    that = this;
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  computed: {
    maxHeight() {
      return this.app.screenHeight - 300;
    },
  },
  methods: {
    initChart(flag = false) {
      this.chart = echarts.init(this.$refs.stageTasks);
      this.chart.setOption({
        tooltip: {},
        // title: {
        //   text: "顶层任务",
        //   left: "center",
        //   top: 10,
        // },
        legend: {
          data: ["未开始", "进行中", "完成", "延期完成", "延期未完成"],
          y: "bottom",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "80px",
          containLabel: true,
        },
        xAxis: {
          minInterval: 1,
          type: "value",
        },
        yAxis: {
          show: false,
          type: "category",
          data: ["stageTasks"],
        },
        series: [
          {
            id: "Unstart",
            name: "未开始",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#409EFF",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Unstart.length],
          },
          {
            id: "Execute",
            name: "进行中",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#E6A23C",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Execute.length],
          },
          {
            id: "Finished",
            name: "完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#67C23A",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Finished.length],
          },
          {
            id: "Dfinished",
            name: "延期完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#9966ff",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Dfinished.length],
          },
          {
            id: "Expired",
            name: "延期未完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#F56C6C",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Expired.length],
          },
        ],
      });
      if (flag) {
        this.chart.on("click", function (params) {
          return;
          that.tableData = that[params.name][params.seriesId];
          that.topen = true;
          console.log(that.tableData);
        });
        this.rend = !this.rend;
      }
    },
    getDataInfo() {
      let type = this.$route.query.type;
      getData(type, this.$route.params.Id).then((response) => {
        if (response.code == 200) {
          this.dataInfo = response.data;
          this.panels.percent = this.dataInfo.percent;
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    getList() {
      getDataList("/pmswbs/list", { projectid: this.$route.params.Id }).then(
        (response) => {
          this.allData = response.rows;
          this.updateData();
          // this.initChart(true);
        }
      );
    },
    getTableColumns(table) {
      getTableCol({ table }).then((response) => {
        this.tableColumns = response.data;
      });
    },
    MakeListTree(list, lists) {
      for (let current of lists) {
        if (current.parentid == list.id) {
          if (list.parents.length) {
            list.parents.forEach((parent) => current.parents.push(parent));
          }
          if (list.isroot !== true) {
            current.parents.push(list.id);
            current.parentid = list.id;
          }
          current = this.MakeListTree(current, lists);
          list.allChildren.push(current.id);
          list.children.push(current.id);
          current.allChildren.forEach((childId) =>
            list.allChildren.push(childId)
          );
        }
      }
      return list;
    },
    ResetListTree(lists) {
      const listById = {};
      var startLevel;
      for (let i in lists) {
        let current = lists[i];
        if (this.dataInfo.phase && current.name == this.dataInfo.phase) {
          this.currentStage = current;
        }
        current.rowIndex = i;
        current.parentid =
          current.parentid == 0 ? current.projectid : current.parentid;
        current.children = [];
        current.allChildren = [];
        current.parents = [];
        listById[current.id] = current;
      }
      return listById;
    },
    SortList2(parentList) {
      var newList = [];
      if (parentList.children && parentList.children.length > 0) {
        for (let li of parentList.children) {
          let item = this.listsById[li];
          newList.push(item);
          let appendList = this.SortList2(item);
          if (appendList.length > 0) {
            newList = newList.concat(appendList);
          }
        }
      }
      return newList;
    },
    updateData() {
      this.dataInfo.parents = [];
      this.dataInfo.children = [];
      this.dataInfo.allChildren = [];
      this.listsById = this.ResetListTree(this.allData);
      this.listTree = this.MakeListTree(this.dataInfo, this.allData);
      this.newList = this.SortList2(this.dataInfo);
      this.currentStage = this.listsById[this.dataInfo.children[0]];
      if (this.dataInfo.phase) {
        for (let id of this.dataInfo.children) {
          if (this.listsById[id].name == this.dataInfo.phase) {
            this.currentStage = this.listsById[id];
            break;
          }
        }
      }
      this.selectPharse(this.currentStage);
    },
    selectPharse(item) {
      (this.panels = {
        percent: 90,
        delayDays: 0,
        delayTasks: [],
        members: [],
      }),
        (this.rateofachieve = []),
        (this.stageTasks = {
          Unstart: [],
          Execute: [],
          Finished: [],
          Dfinished: [],
          Expired: [],
        }),
        (this.allTasks = {
          Unstart: [],
          Execute: [],
          Finished: [],
          Dfinished: [],
          Expired: [],
        }),
        (this.delivers = {
          Unstart: [],
          Execute: [],
          Finished: [],
          Dfinished: [],
          Expired: [],
        }),
        (this.keyTasks = {
          Unstart: [],
          Execute: [],
          Finished: [],
          Dfinished: [],
          Expired: [],
        }),
        (this.currentStage = item);
      this.title = this.currentStage.name;
      this.panels.percent = this.currentStage.percent;
      // this.panels.delayDays = this.currentStage.actual
      //   ? this.currentStage.actual-this.currentStage.estimated
      //   : parseInt(
      //       (new Date().valueOf() -
      //         new Date(this.currentStage.esfinishdate).valueOf()) /
      //         (1000 * 60 * 60 * 24)
      //     );
      for (let id of this.currentStage.allChildren) {
        let item = this.listsById[id];
        let state = this.getStyle(item);
        if (state == "Expired" || state == "Dfinished") {
          this.panels.delayTasks.push(item);
        }
        if (this.currentStage.children.includes(item.id)) {
          this.stageTasks[state].push(item);
        }
        if (item.iskeytask) {
          this.keyTasks[state].push(item);
          let rate = item.actual
            ? (2 - item.actual / item.estimated) * 100 > 100
              ? 100
              : (2 - item.actual / item.estimated) * 100
            : 0;
          this.rateofachieve.push({ name: item.name, rate });
        }
        if (item.isneeddeliverable) {
          this.delivers[state].push(item);
        }
        this.allTasks[state].push(item);
      }
      this.panels.delayDays = this.currentStage.acfinishdate
        ? parseInt(
            (new Date(this.currentStage.acfinishdate).valueOf() -
              new Date(this.currentStage.esfinishdate).valueOf()) /
              (1000 * 60 * 60 * 24)
          )
        : parseInt(
            (new Date().valueOf() -
              new Date(this.currentStage.esfinishdate).valueOf()) /
              (1000 * 60 * 60 * 24)
          );
      this.initChart(true);
    },
    getStyle(row) {
      let state = this.dataFormat("stateid", row.stateid);
      if (state == "创建") {
        return "Unstart";
      } else if (state == "完成") {
        if (
          row.acfinishdate &&
          parseInt(
            (new Date(row.acfinishdate).valueOf() -
              new Date(row.esfinishdate).valueOf()) /
              (1000 * 60 * 60 * 24)
          ) <= 0
        ) {
          return "Finished";
        } else {
          return "Dfinished";
        }
      } else {
        if (
          parseInt(
            (new Date().valueOf() - new Date(row.esfinishdate).valueOf()) /
              (1000 * 60 * 60 * 24)
          ) > 0
        ) {
          return "Expired";
        } else {
          return "Execute";
        }
      }
    },
    handleClick(obj) {
      return false;
      if (obj.table) {
        this.getTableColumns(obj.table);
      } else {
        this.getTableColumns("project_wbs");
      }
      this.tableData = this[obj.first][obj.second];
      this.topen = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  background: #fff;
  height: 100%;
  box-sizing: border-box;
  padding: 10px 0;
  position: relative;
  overflow: hidden;
  .top_bg {
    position: absolute;
    width: 100%;
    height: 260px;
    border-radius: 4px 4px 4px 4px;
    top: 0;
    background: #edf5fe url(../../../assets/image/report.png) no-repeat;
    background-size: 235px 150px;
    background-position: calc(100% - 20px) 70px;
    z-index: 0;
  }
  .report_title {
    margin: 0;
    padding: 10px 0 0;
    text-indent: 2em;
    cursor: pointer;
    position: absolute;
    width: 98%;
  }
  .report_all {
    width: 30%;
    height: calc(99% - 70px);
    position: absolute;
    top: 60px;
    left: 20px;
    .el-card {
      height: 100%;
      .listItem {
        height: 68px;
        background: #ffffff;
        border-radius: 10px 10px 10px 10px;
        opacity: 1;
        border: 1px solid #e9ebee;
        line-height: 68px;
        padding: 0 20px;
        position: relative;
        margin: 5px 0;
        .right {
          float: none;
          position: absolute;
          right: 20px;
          span {
            font-size: 40px;
            font-weight: 600;
            color: #333333;
          }
        }
        img {
          width: 48px;
          height: 48px;
          vertical-align: middle;
        }
      }
    }
  }
  .report_stage {
    width: calc(70% - 310px);
    height: 150px;
    position: absolute;
    top: 60px;
    right: 280px;
    .el-card {
      height: 100%;
      width: 100%;
      .stageTasks {
        width: 100%;
        height: 90px;
      }
    }
  }
  .report_tasks{
    // background: #eee;
    width: calc(70% - 40px);
    position: absolute;
    height: calc(99% - 245px);
    bottom: 12px;
    right: 10px;
    display: flex;
    .el-card{
      width: calc(50% - 10px);
      margin: 0 5px;
    }
  }
}
.right {
  float: right;
}
.left {
  float: left;
}
</style>
